package com.lms.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.lms.bean.*;

import com.lms.service.*;

import com.lms.util.MyStringUtils;
import com.lms.util.QueryResult;
import com.lms.util.ResultUtils;
import com.lms.vo.BookVO;
import com.lms.vo.RequestVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("request")
public class RequestController {

    @Autowired
    private RequestService requestService;

    @Autowired
    private BookService bookService;

    @Autowired
    private UserService userService;

    @Autowired
    private RentRecordService rentRecordService;

    @Autowired
    private ReturnRecordService returnRecordService;

    @RequestMapping("delete")
    public String deleteById(Long id) {
        requestService.deleteById(id);
        return "redirect:admin/request-list";
    }

    @RequestMapping("deleteAll")
    public String deleteById(String ids) {
        requestService.deleteAll(ids);
        return "redirect:admin/request-list";
    }


    @RequestMapping("/admin/request-list")
    public String toRequestList(Model model) {
        Long noHandleCount = requestService.findAllNoHandleCount();
        model.addAttribute("noHandleCount",noHandleCount);
        return "admin/request-list";
    }


    @RequestMapping("/admin/request-input")
    public String toRequestInput(Long id, Model model) {
        Request request = requestService.findRequestById(id);
        RequestVO.parse(request);
        model.addAttribute("request", request);
        return "admin/request-input";
    }

    @RequestMapping("handle")
    public String handle(Long id, Long handle, String message) {
        Request request = requestService.findRequestById(id);
        User user1 = request.getUser();
        Book book1 = request.getBook();
        if (0 == request.getActionCode()) {
            //借书请求的处理
            if (0 == handle) {
                //未处理
                request.setHandleCode(handle);
                requestService.save(request);
                return "redirect:admin/request-list";
            } else if (1 == handle) {
                //借书成功
                Long historyRentCount = book1.getHistoryRentCount();
                if (null == historyRentCount || historyRentCount <= 0) {
                    book1.setHistoryRentCount(1L);
                } else {
                    book1.setHistoryRentCount(historyRentCount + 1);
                }

                Long bookNumber = book1.getBookNumber();
                bookNumber = bookNumber - 1;
                book1.setBookNumber(bookNumber);

                bookService.save(book1);

                RentRecord rentRecord = new RentRecord();
                rentRecord.setUser(user1);
                rentRecord.setBook(book1);
                rentRecord.setState(false);
                rentRecord.setRentTime(new Date());
                rentRecord.setBookDeposit(0.1 * book1.getBookPrice());
                Calendar cal = Calendar.getInstance();
                cal.setTime(rentRecord.getRentTime());   //设置当前时间
                cal.add(Calendar.MONTH, 1);
                Date time = cal.getTime();
                rentRecord.setExpectReturnTime(time);

                rentRecordService.save(rentRecord);

                request.setHandleCode(handle);

                if (StringUtils.isEmpty(message)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String str = sdf.format(time);
                    request.setMessage("预计归还时间：" + str);
                } else {
                    request.setMessage(message);
                }
                requestService.save(request);
                return "redirect:admin/request-list";

            } else if (2 == handle) {
                //借书请求被拒绝
                request.setHandleCode(handle);
                request.setMessage(message);
                requestService.save(request);
                return "redirect:admin/request-list";
            }

        } else {
            //还书请求的处理
            if (0 == handle) {
                //未处理
                request.setHandleCode(handle);
                requestService.save(request);
                return "redirect:admin/request-list";
            } else if (3 == handle) {
                //还书成功
                Long bookNumber = book1.getBookNumber();
                bookNumber = bookNumber + 1;
                book1.setBookNumber(bookNumber);
                bookService.save(book1);

                RentRecord rentRecord = rentRecordService.findBy(user1.getUserId(), book1.getBookId());
                rentRecord.setState(true);

                rentRecordService.save(rentRecord);

                ReturnRecord returnRecord = new ReturnRecord();
                returnRecord.setUser(user1);
                returnRecord.setBook(book1);
                returnRecord.setRentTime(rentRecord.getRentTime());
                returnRecord.setReturnTime(new Date());

                returnRecordService.save(returnRecord);

                request.setHandleCode(handle);
                request.setMessage(message);
                requestService.save(request);
                return "redirect:admin/request-list";


            } else if (4 == handle) {
                //还书失败
                request.setHandleCode(handle);
                request.setMessage(message);
                requestService.save(request);
                return "redirect:admin/request-list";
            }
        }
        return "redirect:admin/request-list";
    }


    @RequestMapping("/rentRequest")
    public String rentRequest(Long bookId, HttpSession session, RedirectAttributes redirectAttributes) {
        Request request = new Request();
        request.setId(null);
        request.setActionCode(0L);// 0L == 借书请求   1L == 还书请求
        request.setCreateTime(new Date());
        request.setHandleCode(0L);// 0L == 未处理   1L == 借书成功   2L == 借书请求被拒绝   3L ==  还书成功    4L == 还书失败
        User user = (User) session.getAttribute("user");
        if (user != null) {
            Book book = bookService.findBookById(bookId);
            if (book == null) {
                redirectAttributes.addFlashAttribute("msg", "图书不存在");
                return "redirect:/borrow";
            }
            User user1 = userService.findUserById(user.getUserId());
            request.setUser(user1);
            request.setBook(book);
            requestService.save(request);
            redirectAttributes.addFlashAttribute("msg", "请求发送成功");
            return "redirect:/borrow";
        }
        redirectAttributes.addFlashAttribute("msg", "你还没有登录");
        return "redirect:/borrow";
    }

    @RequestMapping("/returnRequest")
    public String returnRequest(Long bookId, HttpSession session, RedirectAttributes redirectAttributes) {
        Request request = new Request();
        request.setId(null);
        request.setActionCode(1L);// 0L == 借书请求   1L == 还书请求
        request.setCreateTime(new Date());
        request.setHandleCode(0L);// 0L == 未处理   1L == 借书成功   2L == 借书请求被拒绝   3L ==  还书成功    4L == 还书失败
        User user = (User) session.getAttribute("user");
        if (user != null) {
            Book book = bookService.findBookById(bookId);
            if (book == null) {
                redirectAttributes.addFlashAttribute("msg", "图书不存在");
                return "redirect:/borrow";
            }
            User user1 = userService.findUserById(user.getUserId());
            request.setUser(user1);
            request.setBook(book);
            requestService.save(request);
            redirectAttributes.addFlashAttribute("msg", "请求发送成功");
            return "redirect:/borrow";
        }
        redirectAttributes.addFlashAttribute("msg", "你还没有登录");
        return "redirect:/borrow";
    }


    /**
     * @param pageFromLayUI  计数方式是 1,2,3,4...,n  默认为 1 ;
     *                       但是 Pageable.page 的计数方式是 0,1,2,3,...,n-1 默认为 0
     * @param limitFromLayUI 等于 Pageable.size
     * @return 能被 layUI 接受的 JSON, 格式为 { "code": 0, "msg": "OK", count": 14, "data":[{},{},{}] }
     */
    @RequestMapping("all")
    @ResponseBody
    public ResultUtils<RequestVO> findAll(@RequestParam(value = "page", defaultValue = "1") Integer pageFromLayUI,
                                          @RequestParam(value = "limit", defaultValue = "10") Integer limitFromLayUI,
                                          @RequestParam(value = "keyWord", defaultValue = "") String keyWord) {

        QueryResult<RequestVO> queryResult = requestService.queryByKeyWordLike(pageFromLayUI - 1, limitFromLayUI, StringUtils.trimAllWhitespace(keyWord));

        //返回JSON结果
        return ResultUtils.layUITable(queryResult.getTotalCount(), queryResult.getData());


    }


}
